#ifndef INTERFAZ_DE_RED_H
#define INTERFAZ_DE_RED_H

struct Paquete
{
	Uint8* datos;
	int size;
};

class InterfazDeRed
{
	public:
		~InterfazDeRed();
		int Conectar(char *host, int port);
		bool Enviar(const Paquete* paquete);
		Paquete* Poll();
		void Update();
	private:
		int sockfd;
		fd_set ready;
		int maxsock;
};

InterfazDeRed::~InterfazDeRed
{
	close(sockfd);
}

int InterfazDeRed::Conectar(char *host, int port)
{
	sockfd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
	struct hostent *H = gethostbyname(host);

	struct sockaddr_in adr;

	adr.sin_family = AF_INET;
	adr.sin_port = htons(port);
	adr.sin_addr.s_addr = *((unsigned long *) H->h_addr );
	memset(adr.sin_zero,0,8);

	int e = connect(sockfd,(struct sockaddr *) &adr,sizeof(adr));
	return e;
}

bool InterfazDeRed::Enviar(const Paquete* paquete)
{
	return send(sockfd,paquete->datos,paquete->size,0);
}

Paquete* Poll()
{
	
}

void InterfazDeRed::Update(){
	// Limpio el set
	FD_ZERO(&ready);
	// Meto el socket servidor
	FD_SET(sockfd, &ready);
	// El socket mas grande es el unico que tengo: el servidor
	maxsock = sockfd+1;

	timeval timeout; timeout.tv_sec = 1; timeout.tv_usec = 0;
	int active_socks = select(maxsock, &ready, NULL, NULL, &timeout);
	if(active_socks < 0){
		/* La cagamos... */
		cout << "Error en select" << endl;
	}else if(active_socks == 0){
	
	}else{
		/* Si tengo un nuevo mensaje */
		if(FD_ISSET(sockfd,&ready))
			handle_new_data();
	}
}

#endif
